<template>
	<div class="store">
		<view class="searchGood">
			<view style="display: flex;align-items: center;justify-content: space-between;">
				<view class="address">
					<span class="iconfont icon-dingwei1"></span>
					<picker mode="multiSelector" @change="bindRegionChange"
						@columnchange="bindMultiPickerColumnChange" :value="valueRegion" :range="multiArray">
						<view class='acea-row'>
							<view class="picker line1">{{region[1]}}</view>
						</view>
					</picker>
				</view>
				<view class='search acea-row row-between-wrapper'>
					<!-- #ifndef MP -->
					<view class='input acea-row row-between-wrapper'>
						<text class='iconfont icon-sousuo2'></text>
						<input type='text' :value='searchValue'
						:focus="focus" placeholder='点击搜索水站'
						confirm-type='search' @confirm="searchBut"
						placeholder-class='placeholder'
						maxlength="20"></input>
					</view>
					<!-- #endif -->
					<!-- #ifdef MP -->
					<searchBox :searchValue="searchValue" class="searchBox"  @searchChange="searchBut"></searchBox>
					<!-- #endif -->
				</view>
			</view>
			<view class="address-tab">
				<view :class="tabType==1?'check':''" @click="changeTabType(1)">附近水站</view>
				<view :class="tabType==4?'check':''" @click="changeTabType(4)">新店活动</view>
				<view :class="tabType==3?'check':''" @click="changeTabType(3)">营业中</view>
			</view>
		</view>
		
		<!-- :style="item.isNewFlg?'margin-top: 104rpx;padding-bottom: 48rpx;':''" -->
		<div class="storeBox" ref="container">
			<div class="storeBox-box" v-for="(item, index) in storeList" :key="index" @click.stop="checked(item)" :style="item.isNewFlg?'margin-top:80rpx;':''">
				<image src="./dian.png" class="store-img-dian" mode="widthFix" v-if="item.isNewFlg"></image>
				<view v-if="item.isNewFlg" class="store-text-dian" @click.stop="goRule">新人新店活动规则&nbsp;<view class="iconfont icon-you" style="margin-left: 5rpx;"></view></view>
				<div class="storeBox-box-body" :style="item.isNewFlg?'height:280rpx':''" >
					<div class="store-img"><img class="store-img-img" :src="item.image" lazy-load="true" /></div>
					<div class="store-cent-left">
						<div style="display: flex;align-items: center;justify-content: space-between;">
							<div class="store-name">{{ item.name }}</div>
							<span class='store-status' v-if="timeStatus(item.dayTime).status">营业中</span>
							<span class='store-status2' v-else>休息中</span>
						</div>
						<div class="store-address line1" v-if="!jzFlg || (jzFlg && !item.isNewFlg)">
							{{ timeStatus(item.dayTime).time }}
						</div>
						
						<div class="store-address line1" v-if="!jzFlg">
							{{item.detailedAddress }}
						</div>
						<div class="store-address line1" v-if="jzFlg && userInfo.grade>1">
							水机押金：{{item.depositRefund }}/30000
						</div>
						<div class="store-address line1" v-if="jzFlg">
							<p v-if="parseInt(item.todayBuyAmount) > 50000 || userInfo.grade>1">今日配额：{{parseInt(item.todayBuyAmount) }}/60000</p>
							<p v-else>今日配额：可用</p>
						</div>
						<div class="store-address line1" v-if="jzFlg && item.isNewFlg">
							<p>剩余活动配额：{{item.newUserOffNum}}/{{parseInt(item.newUserOffNum)+parseInt(item.newUserLeftNum)}}</p>
						</div>
						<div class="store-distance">
							<div class="store-distance-name">
								<span class="iconfont icon-dingwei1" style="font-size: 28rpx;margin-right: 10rpx;"></span>
								<span class="addressTxt" v-if="item.distance">距离{{ item.distance/1000 }}km</span>
							</div>
							<div style="display: flex;align-items: center;">
								<!-- #ifdef H5 -->
								<!-- <a class="store-phone" :href="'tel:' + item.phone"><span -->
										<!-- class="iconfont2 icon2-a-dianhuadianhua-icon"></span></a> -->
								<!-- #endif -->
								<!-- #ifdef MP || APP-PLUS -->
								<!-- <view class="store-phone" @click="call(item.phone)"><text -->
										<!-- class="iconfont icon2-a-dianhuadianhua-icon"></text></view> -->
								<!-- #endif -->
								<span class="iconfont2 icon2-daohang" style="font-size: 40rpx;" @click.stop="showMaoLocation(item)"></span>
							</div>
						</div>
					</div>
					<!-- <div class="row-right"> -->
						<!-- <div> -->
							
						<!-- </div> -->
						<!-- <div>
							<a class="store-phone" :href="'tel:' + item.phone"><span class="iconfont icon-dadianhua01"></span></a>
						</div> -->
						
					<!-- </div> -->
				</div>
			</div>


			<Loading :loaded="loaded" :loading="loading"></Loading>
		</div>
		<div>
			<!-- <iframe v-if="locationShow && !isWeixin" ref="geoPage" width="0" height="0" frameborder="0" style="display:none;"
			 scrolling="no" :src="
          'https://apis.map.qq.com/tools/geolocation?key=' +
            mapKey +
            '&referer=myapp'
        ">
			</iframe> -->
		</div>
	</div>
</template>

<script>
	import Loading from "@/components/Loading";
	import {
		storeListApi
	} from "@/api/store";
	import {
		getCityList
	} from "@/utils";
	import {
		isWeixin
	} from "@/utils/index";
	// #ifdef H5
	import {
		wechatEvevt,
		wxShowLocation
	} from "@/libs/wechat";
	// #endif
	import searchBox from "@/components/searchBox.vue";
	import {
		mapGetters
	} from "vuex";
	// import cookie from "@/utils/store/cookie";
	const LONGITUDE = "user_longitude";
	const LATITUDE = "user_latitude";
	const MAPKEY = "mapKey";
	export default {
		name: "storeList",
		components: {
			Loading, searchBox
		},
		props: {
			jzFlg: {
				type: null,
				default: 0
			},
			storeType: {
				type: null,
				default: ''
			},
		},
		// computed: mapGetters(["goName"]),
		computed: mapGetters(['userInfo']),
		data() {
			return {
				page: 1,
				limit: 20,
				loaded: false,
				loading: false,
				storeList: [],
				system_store: {},
				// mapKey: cookie.get(MAPKEY),
				locationShow: false,
				user_latitude: 0,
				user_longitude: 0,
				region: ['省', '城市', '区'],
				valueRegion: [0, 0, 0],
				district: [],
				multiArray: [],
				multiIndex: [0, 0, 0],
				cityId: 0,
				searchValue: '',
				focus: false,
				tabType: 1,
			};
		},
		onLoad() {
			
			try {
				this.user_latitude = uni.getStorageSync('user_latitude');
				this.user_longitude = uni.getStorageSync('user_longitude');
			} catch (e) {
				// error
			}
		},
		mounted() {
			console.log(this.userInfo, this.user_latitude && this.user_longitude)
			if (this.user_latitude && this.user_longitude) {
				this.getList();
			} else {
				this.selfLocation();
			}
			if (this.$Cache.getItem('cityList')) {
				//检测城市数据缓存是否过期，有的话从缓存取，没有的话请求接口
				this.district = this.$Cache.getItem('cityList');
				this.initialize();
			} else {
				getCityList().then(res=>{
					this.district = res
					this.initialize();
				})
			}
			// this.$scroll(this.$refs.container, () => {
			//   !this.loading && this.getList();
			// });
		},
		methods: {
			changeTabType(type) {
				if (this.loading) return;
				this.tabType = type
				this.$set(this, 'storeList', []);
				this.page = 1
				this.loaded = false
				this.loading = false
				this.getList()
			},
			timeStatus(timeList) {
				let status = '',time=''
				let list = timeList.split(',')
				// 方法
				function checkAuditTime(startTime, endTime){
				    // 获取当前时间
				    const date  = new Date()
				    // 获取当前时间的年月日
				    const dataStr = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} `
				 
				    // 获取开始时间、结束时间、现在时间的时间戳
						let startDate = new Date((dataStr + startTime).replace(/-/g,'/')).getTime()
						let endDate = new Date((dataStr + endTime).replace(/-/g,'/')).getTime()
				    let nowDate = date.getTime()
				 
				    const s = startDate > endDate // 判断开始时间否大于结束时间
				 
				    if(s) [startDate, endDate] = [endDate, startDate] // 若开始时间否大于结束时间则交换值
				 
				    // 判断现在的时间是否在开始时间和结束时间之间，若s为true则结果取反
				    if(nowDate > startDate && nowDate < endDate){
				        return s ? false : true
				    }else{
				        return s ? true : false
				    }
				}
				 
				// 使用
				if (list.length) {
					time = `营业时间：${(list[0] || '').substring(0,5)}-${(list[1] || '').substring(0,5)}`
					status = checkAuditTime(list[0],list[1])
				}
				return {
					status: status || 0,
					time: time || '无'
				}
			},
			call(phone) {
				uni.makePhoneCall({
					phoneNumber: phone,
				});
			},
			searchBut: function(e) {
				console.log(e)
				let that = this;
				that.focus = false;
				if(e.detail.value){
					this.searchValue =e.detail.value
				} else {
					this.searchValue = ''
				}
				if (that.searchValue.length > 0||that.searchValue||that.searchValue == '') {
					that.page = 1;
					that.$set(that, 'storeList', []);
					uni.showLoading({
						title: '正在搜索中'
					});
					that.loaded = false
					that.loading = false
					that.getList();
					uni.hideLoading();
				} else {
					return this.$util.Tips({
						title: '请输入要搜索的水站',
						icon: 'none',
						duration: 1000,
						mask: true,
					});
				}
			},
			bindRegionChange: function(e) {
				
				let multiIndex = this.multiIndex,
					province = this.district[multiIndex[0]] || {
						child: []
					},
					city = province.child[multiIndex[1]] || {
						child: []
					},
					multiArray = this.multiArray,
					value = e.detail.value;
				this.region = [multiArray[0][value[0]], multiArray[1][value[1]]]
				this.cityId = city.cityId;
				this.valueRegion = [0, 0]
				this.initialize();
				this.loaded = false
				this.loading = false
				this.page = 1;
				this.$set(this, 'storeList', []);
				this.getList();
			},
			bindMultiPickerColumnChange: function(e) {
				let that = this,
					column = e.detail.column,
					value = e.detail.value,
					currentCity = this.district[value] || {
						child: []
					},
					multiArray = that.multiArray,
					multiIndex = that.multiIndex;
				multiIndex[column] = value;
				switch (column) {
					case 0:
						let areaList = currentCity.child[0] || {
							child: []
						};
						multiArray[1] = currentCity.child.map((item) => {
							return item.name;
						});
						break;
					case 1:
						
						break;
					case 2:
			
						break;
				}
				// #ifdef MP || APP-PLUS
				this.$set(this.multiArray, 0, multiArray[0]);
				this.$set(this.multiArray, 1, multiArray[1]);
				// #endif
				// #ifdef H5
				this.multiArray = multiArray;
				// #endif
				this.multiIndex = multiIndex
				// this.setData({ multiArray: multiArray, multiIndex: multiIndex});
			},
			initialize: function() {
				let that = this,province = [],city = [],area = [];
				if (that.district.length) {
					let cityChildren = that.district[0].child || [];
					let areaChildren = cityChildren.length ? (cityChildren[0].child || []) : [];
					that.district.forEach(function(item,i) {
						province.push(item.name);
						if (item.name === that.region[0]) {
							that.valueRegion[0] = i
							that.multiIndex[0] = i
						}
					});
					that.district[this.valueRegion[0]].child.forEach((item,i)=>{
						city.push(item.name);
						if (that.region[1] == item.name) {
							that.valueRegion[1] = i
							that.multiIndex[1] = i
						}
					})
					this.multiArray = [province, city]
				}
			},
			selfLocation() {
				let self = this
				// #ifdef H5
				if (self.$wechat.isWeixin()) {
					self.$wechat.location().then(res => {
						this.user_latitude = res.latitude;
						this.user_longitude = res.longitude;
						uni.setStorageSync('user_latitude', res.latitude);
						uni.setStorageSync('user_longitude', res.longitude);
						self.getList();
					})
				} else {
				// #endif	
					uni.getLocation({
						type: 'wgs84',
						success: (res) => {
							console.log(res)
							try {
								this.user_latitude = res.latitude;
								this.user_longitude = res.longitude;
								uni.setStorageSync('user_latitude', res.latitude);
								uni.setStorageSync('user_longitude', res.longitude);
							} catch {}
							self.getList();
						},
						complete: function() {
							self.getList();
						},
						fail: function() {
							self.getList();
						}
					});
					// #ifdef H5	
				}
				// #endif
				setTimeout(()=>{
					if (this.storeList.length == 0) {
						self.getList();
					}
				}, 1000)
			},
			showMaoLocation(e) {
				let self = this;
				// #ifdef H5
				if (self.$wechat.isWeixin()) {
					self.$wechat.seeLocation({
						latitude: Number(e.latitude),
						longitude: Number(e.longitude)
					}).then(res => {
						console.log('success');
					})
				} else {
					// #endif	
					location.href = `https://mapapi.qq.com/web/mapComponents/locationMarker/v/index.html?type=0&marker=coord:${Number(e.latitude)},${Number(e.longitude)};title:${e.name};addr:${e.address}-${e.detailedAddress}&key=ZEHBZ-B3BHI-OIWGP-U4RDV-DO425-VCBIO&referer=shared_store`;
					// uni.openLocation({
					// 	latitude: Number(e.latitude),
					// 	longitude: Number(e.longitude),
					// 	name: e.name,
					// 	address: `${e.address}-${e.detailedAddress}`,
					// 	success: function(res) {
					// 		console.log('success',res);
					// 	}
					// });
					// #ifdef H5	
				}
				// #endif
			},
			// 选中门店
			checked(e) {
				this.$emit("changeStore", {
					address: e
				});
				// uni.navigateBack();
			},
			goRule() {
				uni.navigateTo({
					url:"/pages/news/news_details/index?id=23"
				})
			},
			// 获取门店列表数据
			getList: function() {
				if (this.loading || this.loaded) return;
				this.loading = true;
				let data = {
					province: this.region[0] == '省'?'':this.region[0],
					city: this.region[1] == '城市'?'':this.region[1],
					keywords: this.searchValue || '',
					tabType: this.tabType,
					latitude: this.user_latitude || "", //纬度
					longitude: this.user_longitude || "", //经度
					page: this.page,
					limit: this.limit
				};
				if (this.jzFlg) {
					data.jzFlg = this.jzFlg
				}
				if (this.storeType != '') {
					data.storeType = this.storeType
				}
				storeListApi(data)
					.then(res => {
						this.loading = false;
						this.loaded = res.data.list.length < this.limit;
						this.storeList.push.apply(this.storeList, res.data.list);
						this.page = this.page + 1;
					})
					.catch(err => {
						this.$dialog.error(err);
					});
			}
		},
		onReachBottom() {
			this.getList();
		}
	};
</script>

<style scoped lang="scss">
	.geoPage {
		position: fixed;
		width: 100%;
		height: 100%;
		top: 0;
		z-index: 10000;
	}

	.storeBox {
		width: 100%;
	}
	.search{
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex: 1;
	}

	.storeBox-box {
		width: 100%;
		background-color: #fff;
		height: auto;
		padding: 26rpx 30rpx;
		border-radius: 20rpx;
		margin-top: 30rpx;
		position: relative;
		
	}
	.storeBox-box-body{
		position: relative;
		z-index: 2;
		align-items: center;
		display: flex;
		justify-content: space-between;
	}

	.store-cent {
		display: flex;
		align-items: center;
		width: 80%;
	}

	.store-cent-left {
		flex: 1;
	}

	.store-img {
		width: 240rpx;
		height: 225rpx;
		flex-shrink: 0;
		margin-right: 20rpx;
		
	}

	.store-img-img {
		width: 100%;
		height: 100%;
		border-radius: 20rpx;
	}
	.store-text-dian{
		display: flex;
		align-items: center;
		font-weight: bold;
		position: absolute;
		top: 0;
		right: 10rpx;
		z-index: 3;
		color: #3A84F0;
		font-size: 26rpx;
		transform: translate(0, -100%);
		
	}
	.store-img-dian {
		position: absolute;
		bottom: 0;
		left: 0%;
		width: 100%;
		z-index: 2;
	}

	.store-name {
		font-weight: 600;
		font-size: 32rpx;
		color: #333333;
		max-width: 240rpx;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		line-height: 45px;
	}
	.store-status2{
		background-color: #F5F5F5;
		color: #999999;
		height: 30rpx;
		font-size: 22rpx;
		line-height: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 5rpx;
		flex-shrink: 0;
	}
	.store-status{
		@include coupons_light_color(theme);
		@include main_color(theme);
		height: 30rpx;
		font-size: 22rpx;
		line-height: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 5rpx;
		flex-shrink: 0;
	}

	.store-address {
		max-width: 360rpx;
		font-size: 26rpx;
		color: #333333;
		line-height: 37rpx;
		margin-bottom: 14rpx;
	}

	.store-phone {
		@include main_color(theme);
		text-decoration: none;
		margin-right: 20rpx;
		font-size: 40rpx;
	}

	.store-distance {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.store-distance-name{
		font-size: 22rpx;
		color: #979797;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.iconfont {
		font-size: 20rpx;
	}

	.row-right {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		width: 33.5%;
	}
	.searchGood .search {
		padding-left: 30rpx;
	}
	
	.searchGood .search {
		/* #ifndef MP */
		padding-top: 20rpx;
		padding-bottom: 20rpx;
		/* #endif */
		/* #ifdef MP */
		position: fixed;
		width: 100%;
		z-index: 9999;
		top: 0;
		/* #endif */
	}
	
	.searchGood .search .input {
		background-color: #F5F6F9;
		border-radius: 33rpx;
		padding: 0 35rpx;
		box-sizing: border-box;
		height: 66rpx;
		display: flex;
		align-items: center;
		justify-content: flex-start;
		width: 100%;
	}
	
	.searchGood .search .input input {
		font-size: 26rpx;
		margin-left: 5px;
		flex: 1;
	}
	
	.searchGood .search .input .placeholder {
		color: #bbb;
	}
	
	.searchGood .search .input .iconfont {
		color: #000;
		font-size: 35rpx;
	}
	
	.searchGood .search .bnt {
		width: 120rpx;
		text-align: center;
		height: 66rpx;
		line-height: 66rpx;
		font-size: 30rpx;
		color: #282828;
	}
	
	.searchGood .title {
		font-weight: 500;
		font-family: PingFang SC, PingFang SC;
		font-size: 28rpx;
		color: #333;
		margin: 50rpx 30rpx 25rpx 30rpx;
	}
	
	.searchGood .list {
		padding-left: 10rpx;
	}
	
	.searchGood .list .item {
		font-size: 26rpx;
		color: #454545;
		padding: 0 21rpx;
		height: 60rpx;
		border-radius: 30rpx;
		line-height: 60rpx;
		border: 1rpx solid #aaa;
		margin: 0 0 20rpx 20rpx;
	}
	
	.searchGood .line {
		border-bottom: 1rpx solid #eee;
		margin: 20rpx 30rpx 0 30rpx;
	}
	.searchBox{
		width: 100%;
	}
	.store{
		margin: 0 24rpx;
		margin-top: 20rpx;
	}
	.address{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.searchGood {
		padding: 0 30rpx;
		background: linear-gradient( 180deg, #FFFFFF 0%, rgba(255,255,255,0) 100%);
		border-radius: 20rpx 20rpx 0px 0px;
	}
	.address span{
		font-size: 36rpx;
		margin-right: 12rpx;
	}
	.address-tab{
		display: flex;
		align-items: center;
		margin-top: 20rpx;
		margin-bottom: 40rpx;
	}
	.address-tab view{
		width: 184rpx;
		height: 70rpx;
		background: #FFFFFF;
		border-radius: 35rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
	}
	.check{
		@include main_bg_color(theme);
		color: #fff;
	}
</style>
